package com.zeroz.zookeeper.basic;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * ZooKeeper连接示例
 */
public class ZkConnectionExample {
    // ZooKeeper连接字符串，连接到我们的三节点集群
    private static final String CONNECT_STRING = "localhost:2181,localhost:2182,localhost:2183";
    // 会话超时时间
    private static final int SESSION_TIMEOUT = 5000;
    // 等待连接建立的同步锁
    private static final CountDownLatch CONNECTED_LATCH = new CountDownLatch(1);

    public static void main(String[] args) {
        try {
            // 创建ZooKeeper客户端
            ZooKeeper zooKeeper = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    System.out.println("接收到事件：" + event);
                    // 当连接状态变为已连接时，释放锁
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        System.out.println("已成功连接到ZooKeeper集群！");
                        CONNECTED_LATCH.countDown();
                    }
                }
            });

            // 等待连接建立
            System.out.println("正在连接到ZooKeeper集群...");
            CONNECTED_LATCH.await();

            // 获取会话ID
            System.out.println("当前会话ID: 0x" + Long.toHexString(zooKeeper.getSessionId()));
            
            // 使用完成后关闭连接
            zooKeeper.close();
            System.out.println("连接已关闭");
        } catch (IOException | InterruptedException e) {
            System.err.println("连接ZooKeeper时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
} 